﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RentHouse.Service;
using RentHouse.Common;
using RentHouse.DTO;
using RentHouse.IService;
using RentHouse.Service.Entities;
using System.Web.Security;
using System.Web;

namespace RentHouse.Service
{
    public class LoginService : ILoginService
    {    
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginDTO"></param>
        /// <returns></returns>
        public AjaxResult GetLogin(LoginDTO loginDTO)
        {
            using (var db = new RentHouseContext())
            {
                var model = new BaseService<T_AdminUsers>(db);
                var result= model.Get(e => e.PhoneNum == loginDTO.PhoneNum);
                if (result!=null)
                {
                
                    if (result.PasswordHash== CommonHelper.CalcMD5(loginDTO.Password+result.PasswordSalt))
                    {  
                        //登录成功添加cookie
                        var userModel = new LoginAdminDTO
                        {   
                            CityId=result.CityId==null ? 0: (long)result.CityId,
                            Id=result.Id,
                            Name=result.Name,
                            PhoneNum=result.PhoneNum,
                            RoleName=result.T_Roles.FirstOrDefault().Name
                        };
                        SetUserData(userModel);
                    return new AjaxResult(ResultState.Success, "登录成功");

                    }
                    else
                    {
                        return new AjaxResult(ResultState.Error, "登录失败");

                    }
                }
                else
                {
                    return new AjaxResult(ResultState.Error, "该账号不存在");
                }
               
            }
        }
        
        public void SetUserData(LoginAdminDTO loginDTO)
        {
            //获取用户数据转成json
            var userData = loginDTO.ToJson();
            // 4.2、创建票据FormsAuthenticationTicket(对票据进行加密FormsAuthentication.Encrypt)（https://technet.microsoft.com/zh-cn/library/system.web.security.formsauthenticationticket.version）        
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, "loginUser", DateTime.Now, DateTime.Now.AddDays(1), false, userData);
            // 4.3、票据加密FormsAuthentication.Encrypt
            var ticketEncrypt=FormsAuthentication.Encrypt(ticket);
            //4.4、创建Cookie HttpCookie（）
            HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName,ticketEncrypt);
            httpCookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);
            //httpCookie.Path = FormsAuthentication.FormsCookiePath;
            //httpCookie.Domain = FormsAuthentication.CookieDomain;
            //httpCookie.HttpOnly = true;
            //httpCookie.Secure = FormsAuthentication.RequireSSL;


            //4.5、获取当前HTTP上下文 HttpContext; 若为空则抛出异常（throw new ArgumentNullException("context为空");）
            HttpContext context = HttpContext.Current;
            if (context==null)
            {
                throw new ArgumentNullException("context为空");
            }
            //4.6、写入Cookie（https://www.cnblogs.com/tzyy/p/4151291.html）（先移除再添加）
            context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            context.Response.Cookies.Add(httpCookie);



        }
    }
}
